package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    private ShopTypeMapper stm;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> shopTypelCache() {
        //1.从redis中去查询商铺的缓存
        String key="shopType_list";
        String shopTypeListJsonString = stringRedisTemplate.opsForValue().get(key);
        //2.对返回结果进行判断
        if (StrUtil.isBlank(shopTypeListJsonString)){
            //未命中，则去数据库中查询所有的shopType，存入一个list中
            List<ShopType> shopTypes = stm.selectList(null);
            if (shopTypes==null){
                return shopTypes;
            }
            //将shopType的list集合转换json字符串存入redis中充当缓存
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypes));
            return shopTypes;
        }
        List<ShopType> shopTypes = JSONUtil.toList(shopTypeListJsonString, ShopType.class);
        return shopTypes;
    }
}
